<template>
  <div class="top">
    <van-form @submit="onSubmit" class="fom">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="mobile"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          color="#74ebd5"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import mit from "../configuration/mitt";
import { userLogin } from "../axios/http";
import { useStore } from "vuex";
import { Toast } from "vant";
import "vant/es/toast/style";
const router = useRouter();
const username = ref<any>("");
const password = ref<any>();
const store = useStore();
const onSubmit = async (values: string) => {
  console.log("submit", values);
  let acc = await userLogin(username.value, password.value);
  if (acc && acc.data._token) {
    console.log(acc.data);
    // 保存 token 信息
    store.commit("obtain", acc.data._token);
    router.push("/center");
  } else {
    Toast.fail("用户名或者密码输入错误，请检查输入！");
  }
};

mit.emit("flag", false);
onBeforeRouteLeave(() => {
  mit.emit("flag", true);
});
</script>
<style scoped lang="scss">
.top {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to right, #d3cce3, #e9e4f0);
}
.fom {
  .van-cell {
    background-color: rgba($color: #fafafa, $alpha: 0.3);
  }
}
</style>
